
const Fly = require("flyio/dist/npm/wx")
const flyhttp = new Fly()
const newFly = new Fly()
import { baseUrl } from './config';

flyhttp.config.baseURL = baseUrl;
/* @desc:不拦截的请求名 */
const unInterceptorUrl = []

//不弹loading的请求名
const unLoadingUrl = []

/* @desc:检测请求名是否需要拦截 */
function checkUrl(resp) {
    let arr = resp.split('?')[0].split('/'), flag = true
    unInterceptorUrl.forEach(item => {
        if (item === arr[arr.length - 2] + '/' + arr[arr.length - 1]) {
            flag = false
        }
    })
    return flag
}

/* @desc:检测不弹loading的请求名*/
function checkLoadUrl(resp) {
    let arr = resp.url.split('/'), flag = true
    unLoadingUrl.forEach(item => {
        if (item === arr[arr.length - 2] + '/' + arr[arr.length - 1]) {
            flag = false
        }
    })
    return flag
}

flyhttp.interceptors.request.use((request) => { 
    if (checkLoadUrl(request)) {
        // wx.showLoading({ title: '拼命加载中...' })
    }
    return request
})
let clickIndex = 0;
flyhttp.interceptors.response.use(function (response) {  
    let slef = this;
    wx.hideLoading();
    if (response.data.code === 401) {    //token失效
        slef.lock();  //锁住http请求 
        return  wx.login({
                    success: function(wxRes) {
                        newFly.get(`${baseUrl}wx/auth`, { code: wxRes.code }, { headers: {} })
                        .then(resData => { 
                            if (resData.data.code == 200&&resData.data.data) { //token 刷新成功
                                wx.setStorageSync('openId', resData.data.data.openid); 
                                wx.setStorageSync('token', resData.data.data.token);
                                wx.setStorageSync('is_register', resData.data.data.is_register); wx.setStorageSync('userInfo', resData.data.data);  
                                clickIndex++;
                                slef.unlock(); //解锁http请求
                                response.request.headers.token = resData.data.data.token;
                                return flyhttp.request(response.request);
                            } 
                        }) 
                    }
                }); 
        
    } else if (response.data.code != 200 && checkUrl(response.engine.responseURL)) {
        console.log(response.data.msg);
        wx.showToast({
            title: response.data.msg,
            icon: 'none'
        })
        return response
    }else{
        // console.log(response);
        return response
    }
})
export default flyhttp